package com.ikas.ai.server.security;

import com.ikas.ai.consts.Consts;
import com.ikas.ai.server.error.UnauthorizedException;
import com.ikas.ai.server.module.system.model.User;
import com.ikas.ai.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hubowei
 * @email hu.bowei@ikasinfo.com
 * @date 2023-8-29 15:13:36
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("URL:{}", request.getRequestURI());
        String token= JwtUtil.getAuthzHeader(request);
        if (StringUtils.isBlank(token)) {
            throw new UnauthorizedException("认证失败");
        }
        String account = JwtUtil.getClaim(token, Consts.ACCOUNT);
        User user = redisUtil.getBean(Consts.PREFIX_USER_LOGIN + account, User.class);
        if (null == user) {
            throw new UnauthorizedException("认证失败");
        }
        TokenUser tokenUser = new TokenUser();
        tokenUser.setAccount(account);
        tokenUser.setUserId(ObjectUtils.defaultIfNull(user.getId(), -1L));
        UserContextHolder.setTokenUser(tokenUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.removeTokenUser();
    }

}
